<template>
  <el-dialog id="edit-dialog" :title="$t('productCenter.appConfig.calendar.in-edit')" :visible.sync="showState" :destroy-on-close="true" :before-close="handleClose" :close-on-click-modal="false" width="80%" @open="nextTick">
    <el-form ref="formValidate" :model="formValidate" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item :label="$t('productCenter.appConfig.calendar.name')" prop="value">
        <el-select v-model="formValidate.value" :placeholder="$t('common.select')" style="width: 100%">
          <el-option :label="$t('productCenter.appConfig.calendar.status')[1]" :value="1" />
          <el-option :label="$t('productCenter.appConfig.calendar.status')[0]" :value="0" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-calendar
          id="editCalendar"
          v-model="value"
          :first-day-of-week="7"
        >
          <template
            slot="dateCell"
            slot-scope="{date, data}"
          >
            <div :class="restDays.includes(data.day) ? 'is-selected' : ''" style="width: 100%;height: 69px" @click="submit(data)">
              <div>{{ data.day.split('-').slice(2).join('-') }}</div><br>
              <div>{{ restDays.includes(data.day) ? $t('productCenter.appConfig.calendar.rest') : '' }}</div>
            </div>
          </template>
        </el-calendar>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('common.operate.cancel') }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.operate.sure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCalendar, changeWorkDay } from '@/api/product'
import { formatDate } from '@/utils/method'
export default {
  name: 'CalendarDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    chooseItem: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      submitLoading: false,
      value: new Date(),
      restDays: [],
      workDays: [],
      formValidate: {
        value: null
      },
      rules: {
        value: [{ required: true, message: this.$t('productCenter.appConfig.calendar.name') + this.$t('common.null'), trigger: 'blur' }]
      }
    }
  },
  computed: {
    showState: {
      get: function() {
        return this.showDialog
      },
      set: function() {
      }
    }
  },
  mounted() {
    this.formValidate = this.chooseItem
    this.getData(formatDate(new Date(this.value), 'yyyy-MM'))
  },
  methods: {
    nextTick() {
      this.$nextTick(() => {
        // 点击前一个月
        const prevBtnNth = document.querySelector(
          '#editCalendar .el-calendar__button-group .el-button-group>button:nth-child(1)')
        prevBtnNth.addEventListener('click', () => {
          this.getData(formatDate(new Date(this.value), 'yyyy-MM'))
        })
        // 点击后一个月
        const prevBtnLast = document.querySelector(
          '#editCalendar .el-calendar__button-group .el-button-group>button:last-child')
        prevBtnLast.addEventListener('click', () => {
          this.getData(formatDate(new Date(this.value), 'yyyy-MM'))
        })
        const listNext = document.getElementsByClassName('next')
        const that = this
        listNext.forEach(v => {
          v.onclick = function() {
            that.getData(formatDate(new Date(that.value), 'yyyy-MM'))
          }
        })
        const listPrev = document.getElementsByClassName('prev')
        listPrev.forEach(v => {
          v.onclick = function() {
            that.getData(formatDate(new Date(that.value), 'yyyy-MM'))
          }
        })
      })
    },
    submit(data) {
      if (this.restDays.includes(data.day)) {
        this.restDays.splice(this.restDays.findIndex(item => item === data.day), 1)
        this.workDays.push(data.day)
      } else {
        this.workDays.splice(this.restDays.findIndex(item => item === data.day), 1)
        this.restDays.push(data.day)
      }
    },
    handleClose() {
      this.$emit('change-dialog', false)
    },
    handleSubmit() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const data = {
            status: this.formValidate.value,
            restDays: this.restDays,
            workDays: this.workDays
          }
          changeWorkDay(data)
            .then(res => {
              this.submitLoading = false
              if (res.success) {
                this.$message.success(this.$t('common.tip.editSuccess'))
                this.$emit('edit-success')
                this.handleClose()
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.$message.error(err.message)
              this.submitLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getData(month) {
      this.loading = true
      const data = {
        yearMonth: month
      }
      getCalendar(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            res.data.forEach(v => {
              if (v.state === 1) {
                this.restDays.push(v.time)
              } else {
                this.workDays.push(v.time)
              }
            })
            this.restDays = Array.from(new Set(this.restDays))
            this.workDays = Array.from(new Set(this.workDays))
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    }
  }
}
</script>

<style scoped>

</style>
